const { login } = require('../controller/user')
const { ResultSuccess, ResultError } = require('../utils/result')
const { set } = require('../db/redis')

const handleUserRouter = (req, res) => {
  // 登录
  if (req.method === 'POST' && req.path === '/api/user/login') {
    const result = login(req.body)
    // const result = login(req.query)
    return result.then(data => {
      if (data.username) {
        // 设置 session
        req.session.username = data.username
        req.session.realname = data.realname

        // 同步到redis
        set(req.sessionId, req.session)

        return new ResultSuccess('登录成功')
      } else {
        return new ResultError('登录失败')
      }
    })
  }
}

module.exports = handleUserRouter
